package com.algebra.util.sensitive;

import com.algebra.util.annotation.FieldSensitive;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Objects;

/**
 * @author al
 * @date 2022/5/25 11:28
 * @description
 */
public class SensitiveSerializer extends JsonSerializer<String> implements JsonContextualSerializer {

    private static ISensitiveStrategy SENSITIVE_STRATEGY = new SensitiveStrategy();
    private String type;

    public SensitiveSerializer() {
    }

    public SensitiveSerializer(String type) {
        this.type = type;
    }

    public static void setSensitiveStrategy(ISensitiveStrategy sensitiveStrategy) {
        SENSITIVE_STRATEGY = sensitiveStrategy;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (null == SENSITIVE_STRATEGY) {
            throw new RuntimeException("You used the annotation `@FieldSensitive` but did not inject `SensitiveStrategy`");
        } else {
            gen.writeObject(Objects.equals("1", RequestDataTransfer.get("skip_sensitive")) ? value : SENSITIVE_STRATEGY.handle(this.type, value));
        }
    }

    @Override
    public JsonSerializer<?> getJsonSerializer(SerializerProvider provider, BeanProperty property) throws JsonMappingException {
        if (Objects.equals(property.getType().getRawClass(), String.class)) {
            FieldSensitive sensitiveInfo = this.getAnnotation(property, FieldSensitive.class);
            if (null != sensitiveInfo) {
                return new SensitiveSerializer(sensitiveInfo.value());
            }
        }
        return provider.findValueSerializer(property.getType(), property);
    }

}
